#include "CUtil.h"
#include <QDir>
#include <QDebug>
#include <QImage>
#include <QPainter>

CUtil::CUtil(QObject *parent)
    : QObject{parent}
{

}

void CUtil::spliceImage(const QString &path)
{
    int imgWidth = 0;
    int imgHeight = 0;
    QDir dir(path);

    QStringList imgList = dir.entryList(QStringList("*.png"), QDir::NoFilter, QDir::Name);

    if (imgList.isEmpty()) {
        qWarning() << QString("dir:%1 is empty!").arg(path);
        return ;
    }

    foreach (QString fileName, imgList) {
        qDebug() << "fileName:" << fileName;
        QImage image(fileName);

        imgWidth = qMax(imgWidth,image.width());
        imgHeight += image.height();
    }

    qDebug() << QString("拼接图的宽高为:%1x%2").arg(imgWidth).arg(imgHeight);
    QImage imageResult(imgWidth,imgHeight,QImage::Format_ARGB32_Premultiplied);


    QPainter painter(&imageResult);

    int offsetY = 0;
    foreach (QString fileName, imgList) {
        qDebug() << "fileName:" << fileName;
        int y = 0;
        QImage image(fileName);
        QImage cropImage = image.copy(0, y, image.width(), image.height() - y);
        painter.drawImage(0,offsetY,cropImage);
        offsetY += cropImage.height();
    }

    imageResult.save("result.png");
}
